package damngoodcoffee.smart;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.logging.Logger;

import sun.net.www.protocol.http.HttpURLConnection;

public class ResourceReaderImpl implements ResourceReader {
    private static Logger logger = Logger.getLogger(ResourceReaderImpl.class
	    .getCanonicalName());

    public Reader read(String source) throws ResourceReaderException {
	Reader r = null;
	try {
	    URI uri = new URI(source);
	    if (!uri.isAbsolute()) {
		File file = new File(uri.getPath());
		if (!file.exists()) {
		    throw new RuntimeException("The given file " + source
			    + " doesn't exists..");
		}

		r = new BufferedReader(new FileReader(file));
	    } else if (uri.getScheme() != null
		    && uri.getScheme().equals("file")) {
		File file = new File(uri);
		if (!file.exists()) {
		    throw new RuntimeException(
			    "The given file doesn't exists..");
		}

		r = new BufferedReader(new FileReader(file));
	    } else {
		URL url = uri.toURL();
		HttpURLConnection connection = (HttpURLConnection) url
			.openConnection();
		connection.setRequestMethod("GET");
		connection.setRequestProperty("Content-type", "text/html");
		connection.setDoOutput(true);
		connection.setChunkedStreamingMode(1024 * 128);
		connection.connect();
		InputStream in = new BufferedInputStream(connection
			.getInputStream());
		r = new InputStreamReader(in);
	    }
	} catch (URISyntaxException e) {
	    File file = new File(source);
	    if (!file.exists()) {
		throw new RuntimeException("The given file " + source
			+ " doesn't exists..");
	    }

	    try {
		r = new BufferedReader(new FileReader(file));
	    } catch (FileNotFoundException e1) {
		throw new ResourceReaderException(e);
	    }
	} catch (FileNotFoundException e) {
	    throw new ResourceReaderException(e);
	} catch (MalformedURLException e) {
	    throw new ResourceReaderException(e);
	} catch (ProtocolException e) {
	    throw new ResourceReaderException(e);
	} catch (IOException e) {
	    throw new ResourceReaderException(e);
	}
	return r;
    }
}
